//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/subject/submit_paper_model.dart';
import 'package:hktk_app/model/subject/upload_answer_model.dart';
import 'package:hktk_app/pages/question/result_page.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/encrypt_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/my_util.dart';

import 'package:hktk_app/util/sz_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/question/calculator_widget.dart';
import 'package:hktk_app/widget/question/question_dtk_widget.dart';
import 'package:hktk_app/widget/question/question_sz_widget.dart';
import 'package:hktk_app/widget/question/whiteboard_widget.dart';

/// 做题页面底部组件
class QuestionBottomWidget extends StatefulWidget {
  /// 试题模式，ture-答题，false-背题
  final QuestionTypeEnum type;

  const QuestionBottomWidget({
    super.key,
    required this.type,
  });

  @override
  State<QuestionBottomWidget> createState() => _QuestionBottomWidgetState();
}

class _QuestionBottomWidgetState extends State<QuestionBottomWidget> {
  late BuildContext _context;

  /// 是否显示工具箱
  late bool _showGjx;

  /// 工具箱浮动显示组件
  OverlayEntry? _gjxEntry;

  /// 草稿纸浮动显示组件
  OverlayEntry? _cgzEntry;

  /// 计算器浮动显示组件
  OverlayEntry? _jsqEntry;

  /// 对应试题下标
  late int _index;

  /// 监听方法
  late StreamSubscription<EventQuestionOnPage> _eventOnPage;

  late StreamSubscription<EventQuestionExamData> _eventExamData;

  late StreamSubscription<EventQuestionQk> _eventQk;

  late StreamSubscription<EventQuestionDtShowJx> _eventDtShowJx;

  @override
  void initState() {
    super.initState();
    debugPrint("questionBottomWidget 组件 -> initState 方法执行 ===> ");
    debugPrint("");
    _showGjx = false;
    _index = dataUtilComm.paperData!.lastIndex;

    // 监听方法
    _eventOnPage = eventBus.on<EventQuestionOnPage>().listen((event) {
       if (widget.type == event.type) {
        setState(() {
          _index = event.index;
        });
      }
    });
    _eventExamData = eventBus.on<EventQuestionExamData>().listen((event) {

      if (event.exam == 2) {
        _submitThePaper();
      }
    });
    _eventQk = eventBus.on<EventQuestionQk>().listen((event) {
    _qkDtkList();
    });
    _eventDtShowJx = eventBus.on<EventQuestionDtShowJx>().listen((event) {
    if (_index == event.index) {
        setState(() {});
      }
    });
  }

  @override
  void dispose() {
    super.dispose();

    _closeGjxEntry();
    _eventOnPage.cancel();
    _eventExamData.cancel();
    _eventQk.cancel();
    _eventDtShowJx.cancel();
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    return Container(
      height: 98,
      padding: EdgeInsets.symmetric(horizontal: 45),
      decoration: BoxDecoration(
        color: getColorWhite1(szYjms: szUtilComm.szInfo.yjms),
        boxShadow: [
          BoxShadow(
            color: colorBlack2,
            offset: Offset(0, -1),
            blurRadius: 4,
            spreadRadius: 0,
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _showIconJj(),
          _showIcons(),
        ],
      ),
    );
  }

  /// 交卷店铺显示
  _showIconJj() {
    if (widget.type == QuestionTypeEnum.exam) {
      return _showBottomIcon(
        svgUrl: "images/question/bottom_jj.svg",
        title: "交卷",
        onTapFun: _onTapFunJj,
      );
    } else {
      // 占位使用
      return SizedBox(width: 0, height: 80);
    }
  }

  /// 显示对应图标
  _showBottomIcon({
    required String svgUrl,
    required String title,
    required Function() onTapFun,
    bool showColor = false,
  }) {
    return GestureDetector(
      onTap: onTapFun,
      // child: Container(),
      child: SizedBox(
        height: 65,
        // child: Center(
        //   child: Text(
        //     "",
        //     style: FontUtil.fontBlack1(18, szYjms: szUtilComm.szInfo.yjms),
        //   ),
        // ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SvgPicture.asset(
              svgUrl,
              width: 32,
              height: 32,
              color: showColor
                  ? getColorBlue1(szYjms: szUtilComm.szInfo.yjms)
                  : getColorBlack1(szYjms: szUtilComm.szInfo.yjms),
            ),
            Text(
              title,
              style: FontUtil.fontBlack1(18, szYjms: szUtilComm.szInfo.yjms),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示图标数组
  _showIcons() {
    bool showIconJx = widget.type == QuestionTypeEnum.answer ||
        widget.type == QuestionTypeEnum.memory;
    return Flexible(child: Row(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        if (showIconJx)
          _showBottomIcon(
            svgUrl: "images/question/bottom_jx.svg",
            title: "解析",
            onTapFun: _onTapFunJx,
            // showColor: dataUtilComm.paperData!.dtkList[_index].showJx,
          ),

        _showBottomIcon(
          svgUrl: "images/question/bottom_dtk.svg",
          title: "答题卡",
          onTapFun: _onTapFunDtk,
        ),

        // _showBottomIcon(
        //   svgUrl: "images/question/bottom_gjx.svg",
        //   title: "工具箱",
        //   onTapFun: _onTapFunGjx,
        //   showColor: _showGjx,
        // ),

        _showBottomIcon(
          svgUrl: "images/question/bottom_sz.svg",
          title: "设置",
          onTapFun: _onTapFunSz,
        ),
      ],
    ));
  }

  /// 创建工具箱显示Widget方法
  // void _createGjxEntry() {
  //   debugPrint("questionBottomWidget 组件 -> 创建工具箱显示Widget方法执行 ===> ");
  //   double bottom = MediaQuery.of(_context).padding.bottom;
  //   double gjxBottom = bottom + 108;
  //   _gjxEntry = OverlayEntry(builder: (context) {
  //     return Positioned(
  //       bottom: gjxBottom,
  //       right: 50,
  //       child: Material(
  //         child: Container(
  //           width: 188,
  //           height: 176,
  //           decoration: BoxDecoration(
  //             color: szUtilComm.szInfo.yjms ? colorBlack14 : colorWhite1,
  //             borderRadius: BorderRadius.all(Radius.circular(8)),
  //             boxShadow: [
  //               BoxShadow(
  //                 color: colorBlack2,
  //                 offset: Offset(0, 2),
  //                 blurRadius: 10,
  //                 spreadRadius: 0,
  //               ),
  //             ],
  //           ),
  //           child: Column(
  //             children: [
  //               _showGjxItem("草稿纸", _onTapFunGjxCgz, true),
  //               _showGjxItem("计算器", _onTapFunGjxJsq, false),
  //             ],
  //           ),
  //         ),
  //       ),
  //     );
  //   });
  // }

  /// 关闭工具箱方法
  void _closeGjxEntry() {
    if (_showGjx) {
      _gjxEntry!.remove();
      setState(() {
        _showGjx = false;
      });
    }
  }

  /// 显示工具箱的item，如草稿箱
  _showGjxItem(String title, Function() onTapFun, bool showBorder) {
    return GestureDetector(
      onTap: onTapFun,
      child: Container(
        height: 88,
        margin: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          border: showBorder
              ? Border(
            bottom: BorderSide(color: colorBlack5, width: 1),
          )
              : null,
        ),
        child: Center(
          child: Text(
            title,
            style: FontUtil.fontBlack1(30, szYjms: szUtilComm.szInfo.yjms),
          ),
        ),
      ),
    );
  }

  /// 显示答题卡的弹出层
  _showPopupDtk() async {
    // 获取弹出层高度
    var height = MediaQuery.of(_context).size.height;
    double sheetHeight = height * 0.5;
    showModalBottomSheet<int>(
      context: _context,
      // 设置底部弹出框全屏显示
      isScrollControlled: true,
      // 自定义弹出层高度
      constraints: BoxConstraints(maxHeight: sheetHeight),
      // 自定义圆角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      builder: (context) {
        return QuestionDtkWidget(
          list: _getBogDtkList(),
          szYjms: szUtilComm.szInfo.yjms,
          type: widget.type,
          doing: _getDtkDoing(),
        );
      },
    );
  }

  /// 计算答题卡相关数据
  _getBogDtkList() {
    List<BogInfoModel> list = dataUtilComm.paperData!.bogDtkList;
    List<DtkInfoModel> dtkList = dataUtilComm.paperData!.dtkList;
    int i = 0;
    for (BogInfoModel bog in list) {
      int end = i + bog.total;
      bog.dtkList = dtkList.sublist(i, end);
      i = end;
    }
    return list;
  }

  /// 答题卡里面是否有做题数据
  _getDtkDoing() {
    List<DtkInfoModel> dtkList = dataUtilComm.paperData!.dtkList;
    for (DtkInfoModel dtk in dtkList) {
      if (dtk.ansType != AnswerTypeEnum.notDone) {
        return true;
      }
    }
    return false;
  }

  /// 显示设置的弹出层
  _showPopupSz() async {
    // 获取弹出层高度
    double bottom = MediaQuery.of(_context).padding.bottom;
    double sheetHeight = bottom + 448;
    showModalBottomSheet<Map<String, dynamic>>(
      context: _context,
      // 设置底部弹出框全屏显示
      isScrollControlled: true,
      // 自定义弹出层高度
      constraints: BoxConstraints(maxHeight: sheetHeight),
      // 自定义圆角
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30),
          topRight: Radius.circular(30),
        ),
      ),
      builder: (BuildContext context) {
        return const QuestionSzWidget();
      },
    );
  }

  /// 创建草稿纸
  void _createCgzEntry() {
    debugPrint('questionBottomWidget 组件 -> 创建草稿纸的widget方法执行 ===> ');
    // 创建一个OverlayEntry对象
    _cgzEntry ??= OverlayEntry(builder: (context) {
      return Positioned.fill(
        child: WhiteboardWidget(
          onTapFunClose: _closeCgzEntry,
        ),
      );
    });
    // 往Overlay中插入插入OverlayEntry
    Overlay.of(_context).insert(_cgzEntry!);
  }

  /// 关闭草稿纸方法
  _closeCgzEntry() {
    debugPrint("questionBottomWidget 组件 -> 关闭草稿纸方法执行 ===> ");
    _cgzEntry!.remove();
  }

  /// 创建计算器方法
  // void _createJsqEntry() {
  //   debugPrint("questionBottomWidget 组件 -> 创建计算器的widget方法执行 ===> ");
  //   // 创建一个OverlayEntry对象
  //   _jsqEntry ??= OverlayEntry(builder: (context) {
  //     return Positioned.fill(
  //       child: CalculatorWidget(
  //         onTapFunClose: _closeJsqEntry,
  //       ),
  //     );
  //   });
  //   // 往Overlay中插入插入OverlayEntry
  //   Overlay.of(_context).insert(_jsqEntry!);
  // }

  /// 关闭计算器方法
  // _closeJsqEntry() {
  //   debugPrint("questionBottomWidget 组件 -> 关闭计算器方法执行 ===> ");
  //   _jsqEntry?.remove();
  // }

  /// 解析点击方法
  _onTapFunJx() {
    DtkInfoModel dtk = dataUtilComm.paperData!.dtkList[_index];
    debugPrint("questionBottomWidget 组件 -> 你点击了解析 ===> ${dtk.showJx}");
    _closeGjxEntry();
    if (widget.type == QuestionTypeEnum.answer &&
        dtk.ansType != AnswerTypeEnum.notDone) {
      dataUtilComm.paperData!.dtkList[_index].showJx = !dtk.showJx;
      eventBus.fire(EventQuestionShowJx(index: dtk.index));
      setState(() {});
    }
  }

  /// 答题卡点击方法
  _onTapFunDtk() {
    debugPrint("questionBottomWidget 组件 -> 你点击了答题卡 ===> ");
    _closeGjxEntry();
    _showPopupDtk();
  }

  /// 工具箱点击方法
  // _onTapFunGjx() {
  //   debugPrint("questionBottomWidget 组件 -> 你点击了工具箱 ===> $_showGjx");
  //   if (!_showGjx) {
  //     if (_gjxEntry == null) {
  //       _createGjxEntry();
  //     }
  //     Overlay.of(_context).insert(_gjxEntry!);
  //     setState(() {
  //       _showGjx = true;
  //     });
  //   } else {
  //     _closeGjxEntry();
  //   }
  // }

  /// 设置点击方法
  _onTapFunSz() {
    debugPrint("questionBottomWidget 组件 -> 你点击了设置 ===> ");
    _closeGjxEntry();
    _showPopupSz();
  }

  /// 草稿纸点击方法
  // _onTapFunGjxCgz() {
  //   debugPrint("questionBottomWidget 组件 -> 你点击了草稿纸 ===> ");
  //   _closeGjxEntry();
  //   _createCgzEntry();
  // }

  /// 计算器点击方法
  // _onTapFunGjxJsq() {
  //   _closeGjxEntry();
  //   _createJsqEntry();
  // }

  /// 交卷点击方法
  _onTapFunJj() {
    if (widget.type == QuestionTypeEnum.exam) {
      // NavigatorUtil.push(_context, ResultPage(id: dataUtilComm.paperData!.id));
      // 开启加载框，发送信息获取当前页面的答案
      ToastUtil.loadingBoxShow(_context);
      DtkInfoModel dtk = dataUtilComm.paperData!.dtkList[_index];
      if (MyUtil.getDXT(dtk.type) || MyUtil.getPDT(dtk.type)) {
        _submitThePaper();
      } else {
        eventBus.fire(EventQuestionExamJj(id: dtk.id, exam: 2));
      }
    }
  }

  /// 交卷执行方法
  _submitThePaper() {
    _uploadJj().then((Map<String, dynamic> map) {
      // 加载完成，关闭加载框
      ToastUtil.loadingBoxRemove();
      if (map["suc"]) {
        SubmitPaperModel submitPaperModel = map["submitPaperModel"];
        SubmitPaperModel data = map["data"];
        CtEnum rType = dataUtilComm.paperData!.rType;
        if (rType == CtEnum.paperRecordRandomFormPaper) {
          // 随机组卷跳转结果页面
          Navigator.pushNamedAndRemoveUntil(context, "/result", (route)  {
            return route.settings.name == "/tab"||route.settings.name == "/";
          },arguments: {
            "submitModel": submitPaperModel,
            "paperRecords": data,
          });
        } else {
          eventBus.fire(EventPaperSubmit());
          // 试卷考试跳转结果页面

          Navigator.pushReplacementNamed(context, "/result",arguments: {
            "submitModel": submitPaperModel,
            "paperRecords": data,
          });
        }
      } else {
        // 加载失败，提示
        ToastUtil.show(context: _context, msg: map["msg"]);
      }
    });
  }

  /// 交卷接口
  Future<Map<String, dynamic>> _uploadJj() async {
    Map<String, dynamic> map = {};
    try {
      DataModel dataModel = dataUtilComm.dataModel;
      PaperDataModel paperData = dataUtilComm.paperData!;
      SubmitPaperModel submitPaperModel = await _submitPaper(
        dataModel: dataModel,
        paperData: paperData,
      );
      SubmitPaperModel data = await _paperRecords(
        dataModel: dataModel,
        recordsId: paperData.id,
      );
      map["submitPaperModel"] = submitPaperModel;
      map["data"] = data;
      map["suc"] = true;
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {

        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 试卷提交接口
  Future<SubmitPaperModel> _submitPaper({
    required DataModel dataModel,
    required PaperDataModel paperData,
  }) async {
    Map<String, dynamic> data = {};
    String lastId = paperData.dtkList[_index].id;
    for (DtkInfoModel dtk in paperData.dtkList) {
      if (dtk.ansType != AnswerTypeEnum.notDone) {
        // 储存数据
        lastId = dtk.id;
        data[dtk.id] = _getUploadAns(dtk);
      }
    }
    int end = DateTime.now().millisecondsSinceEpoch;
    String sign = EncryptUtil.getMd5Sign(time: end.toString());
    // 发送请求
    return await SubjectDao.submitPaperAnswer(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      recordsId: paperData.id,
      seconds: end - paperData.startDate,
      imageCheck: false,
      timestamp: end,
      sign: sign,
      lastId: lastId,
      data: data,
    );
  }

  /// 格式化试卷方法
  UploadAnswerModel _getUploadAns(DtkInfoModel dtk) {
    String as = dtk.getUserAnsStr();
    return UploadAnswerModel(
      qt: dtk.type.code,
      tr: dtk.type.desc,
      st: dtk.st,
      as: MyUtil.getPDT(dtk.type) ? int.parse(as) : as,
      sn: dtk.sign,
      t: dtk.ansDate ?? 0,
      asb: dtk.answerBase64,
    );
  }

  /// 内部打开试卷结果查看
  Future<SubmitPaperModel> _paperRecords({
    required DataModel dataModel,
    required String recordsId,
  }) async {
    return await SubjectDao.paperRecordsInlineResult(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      recordsId: recordsId,
      structure: false,
    );
  }

  /// 清空答题卡相关数据方法
  _qkDtkList() {
    List<DtkInfoModel> dtkList = dataUtilComm.paperData!.dtkList;
    for (DtkInfoModel dtk in dtkList) {
      dtk.showJx = false;
      dtk.ansDate = null;
      dtk.ansType = AnswerTypeEnum.notDone;
      dtk.userAns = [];
    }
    dataUtilComm.paperData!.dtkList = dtkList;
    Future.delayed(const Duration(seconds: 1), () {
      // 跳转至第一页,延时1秒执行
      eventBus.fire(EventQuestionOnDtk(index: 0));
    });
    setState(() {});
  }
}
